package modules.ASK.main

import chisel3._
import chisel3.util._
import modules.ASKReceier.main.{ASKReceiver, ASKReceiverDebug}
import modules.ASKSender.main.ASKSender
import utils.GlobalConfigLoader.GlobalConfig
import utils.Utils.counter

class ASK(maxDataBytes: Int = 8)(implicit c: GlobalConfig) extends Module {
  val io = IO(new Bundle {
    val clockOffset = Input(UInt(8.W))
    val dataSource = Input(UInt(64.W))
    val start = Input(Bool())
    val debug = if (c.ask.debug) Some(new ASKReceiverDebug(maxDataBytes)) else None
    val dacOut = Output(UInt(8.W))
  })

  val senderCnt = RegInit(0.U(log2Ceil(c.ask.clkPerBit).W))
  val receiver = Module(new ASKReceiver)
  if (c.ask.debug) receiver.io.debug.get <> io.debug.get
  io.dacOut := receiver.io.dacOut

  counter(senderCnt, c.ask.clkPerBit)
  val senderCntWithOffset = (senderCnt + io.clockOffset).asTypeOf(senderCnt.cloneType)
  val senderClock = senderCntWithOffset >= io.clockOffset && senderCntWithOffset < (c.ask.clkPerBit / 2).U + io.clockOffset
  withClock(senderClock.asClock) {
    val sender = Module(new ASKSender(maxDataBytes = maxDataBytes))
    sender.io.start.get := io.start
    sender.io.packSource.get := io.dataSource
    receiver.io.adc := sender.io.dacOut
  }
}